<template>
  <div class="app-container">
    <!--搜索区域-->
    <el-form size="mini" :inline="true" :model="searchForm">
      <el-form-item>
        <el-input v-model="searchForm.name" placeholder="角色" @keyup.enter.native="searchHandle"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" :loading="searchLoading" @click="searchHandle">
          查询
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" icon="el-icon-plus" @click="insertHandle()">添加</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" icon="el-icon-delete" @click="deleteHandle()" :disabled="multipleSelection.length === 0">
          删除
        </el-button>
      </el-form-item>
    </el-form>
    <!--数据表格-->
    <el-table
      v-loading="listLoading"
      element-loading-text="加载中，请稍后..."
      size="mini"
      border
      fit
      highlight-current-row
      :data="roleList"
      @selection-change="selectionChangeHandle"
    >
      <el-table-column prop="id" type="selection" fixed/>
      <el-table-column label="名称" prop="name"/>
      <el-table-column label="描述" prop="description"/>
      <el-table-column label="状态" align="center" width="70">
        <template slot-scope="scope">
          <el-tag size="mini" :type="scope.row.status | statusFilter">
            {{ scope.row.status | statusTextFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建人" prop="createUsername"/>
      <el-table-column label="更新人" prop="updateUsername"/>
      <el-table-column label="创建时间" align="center" width="150" :formatter="createTimeFormatHandle"/>
      <el-table-column label="更新时间" align="center" width="150" :formatter="updateTimeFormatHandle"/>
      <el-table-column label="操作" fixed="right" align="center" width="290">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="updateHandle(scope.row)">编辑</el-button>
          <el-button type="success" size="mini" @click="authHandle(scope.row)">授权</el-button>
          <el-button type="warning" size="mini" @click="assignHandle(scope.row)">分配</el-button>
          <el-button type="danger" size="mini" @click="deleteHandle(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination :total="searchForm.total" :currentPage="searchForm.currentPage" :pageSize="searchForm.pageSize" @size-change="pageSizeChangeHandle" @current-change="currentPageChangeHandle"></pagination>
    <!-- 添加角色 -->
    <role-insert :visible.sync="insertVisible" @reloadTable="searchHandle"/>
    <!-- 更新角色 -->
    <role-update :visible.sync="updateVisible" :row-data="rowData" @reloadTable="searchHandle"/>
    <!-- 角色授权 -->
    <role-auth :visible.sync="authVisible" :roleId="roleId" reloadTable="searchHandle"/>
    <!-- 角色分配 -->
    <role-assign :visible.sync="assignVisible" :roleId="roleId"/>
  </div>
</template>

<script>
  import Pagination from './../../components/Pagination'
  import RoleInsert from './components/role-insert'
  import RoleAuth from './components/role-authorize'
  import RoleAssign from './components/role-assign'
  import RoleUpdate from './components/role-update'
  import { parseTime } from '@/utils/CliUtils'

  export default {
    components: {
      'pagination': Pagination,
      'role-insert': RoleInsert,
      'role-auth': RoleAuth,
      'role-update': RoleUpdate,
      'role-assign': RoleAssign
    },
    filters: {
      statusFilter(status) {
        const statusMap = { 0: 'success', 1: 'gray' }
        return statusMap[status]
      },
      statusTextFilter(status) {
        const statusTextMap = { 0: '启用', 1: '停用' }
        return statusTextMap[status]
      }
    },
    data() {
      return {
        roleList: null,
        listLoading: true,
        searchForm: {
          name: '',
          // 分页字段（父子组件都会用到）
          currentPage: 1,
          pageSize: 20,
          total: 0
        },
        searchLoading: false,
        multipleSelection: [],
        // 子组件使用
        insertVisible: false,
        updateVisible: false,
        authVisible: false,
        assignVisible: false,
        rowData: null,
        roleId: ''
      }
    },
    created() {
      this.listHandle()
    },
    methods: {
      /**
       * 查询所有角色
       */
      listHandle() {
        this.listLoading = true
        this.searchLoading = true
        this.AjaxUtils.get('/role/listRole', this.searchForm).then((response) => {
          this.listLoading = false
          this.searchLoading = false
          // 表格数据
          this.roleList = response.data
          // 数据总条数
          this.searchForm.total = response.total
        }).catch(() => {
          this.listLoading = false
          this.searchLoading = false
        })
      },
      /**
       * Table组件格式化创建时间
       * @param row
       * @returns {*}
       */
      createTimeFormatHandle(row) {
        return parseTime(new Date(row.createTime))
      },
      /**
       * Table组件格式化更新时间
       * @param row
       * @returns {*}
       */
      updateTimeFormatHandle(row) {
        return parseTime(new Date(row.updateTime))
      },
      /**
       * 模糊搜索
       */
      searchHandle() {
        this.searchForm.currentPage = 1
        this.searchForm.pageSize = 20
        this.listHandle()
      },
      /**
       * 分页：每页显示数量发生变化时
       * @param val
       */
      pageSizeChangeHandle(val) {
        this.searchForm.pageSize = val
        this.listHandle()
      },
      /**
       * 分页：当前页发生变化时
       * @param val
       */
      currentPageChangeHandle(val) {
        this.searchForm.currentPage = val
        this.listHandle()
      },
      /**
       * Table组件多选时
       * @param val
       */
      selectionChangeHandle(val) {
        this.multipleSelection = val
      },
      /**
       * 显示添加角色子组件
       */
      insertHandle() {
        this.insertVisible = true
      },
      /**
       * 显示更新角色子组件
       * @param row
       */
      updateHandle(row) {
        this.updateVisible = true
        this.rowData = row
      },
      /**
       * 显示插入角色授权子组件
       * @param row
       */
      authHandle(row) {
        this.authVisible = true
        this.roleId = row.id
      },
      /**
       * 显示插入角色分配子组件
       * @param row
       */
      assignHandle(row) {
        this.assignVisible = true
        this.roleId = row.id
      },
      /**
       * 删除角色 TODO
       * @param row
       */
      deleteHandle(row) {
        // make
        let ids = ''
        this.multipleSelection.forEach(item => {
          ids = ids + item.id + ','
        })
        if (row) {
          ids = row.id
        }
        // ajax
        // this.ComponentUtils.confirm().then(() => {
        //   this.AjaxUtils.delete('/role/deleteRole', { ids: ids }, true).then((response) => {
        //     if (response.code === 0) {
        //       this.searchHandle()
        //     }
        //   }).catch(() => {
        //   })
        // }).catch(() => {
        // })
        // 方案2 TODO 代码臃肿 需要封装
        this.$confirm('确定执行此操作吗？', '提示', {
          type: 'warning',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          closeOnClickModal: false,
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              // ajax
              instance.confirmButtonLoading = true
              this.AjaxUtils.delete('/role/deleteRole', { ids: ids }, true).then((response) => {
                if (response.code === 0) {
                  instance.confirmButtonLoading = false
                  done()
                  this.searchHandle()
                }
              }).catch(() => {
                instance.confirmButtonLoading = false
                done()
              })
            } else {
              done()
            }
          }
        }).then(() => {
          console.log('点了确定')
        }).catch(() => {
          console.log('点了取消')
        })
      }
    }
  }
</script>
